"""
利用Python进行数据分析

NumPy
"""
import numpy as np
from numpy.linalg import inv, qr


def save_data_to_byte():
    """
    将数据以二进制格式保存到磁盘
    :return:
    """
    attr = np.arange(10)
    print(attr)
    np.save('some_attr', attr)

    attr2 = np.load('some_attr.npy')
    print(attr2)

    np.savez('array_archive.npz', a=attr2, b=attr2)
    arch = np.load('array_archive.npz')
    print(arch['a'])
    print(arch['b'])


def save_write_txt():
    """
    存取文本文件
    :return:
    """
    attr = np.random.randn(3, 3)
    np.savetxt('attr_3_3.txt', attr, delimiter=',')

    attr2 = np.loadtxt('attr_3_3.txt', delimiter=',')
    print(attr2)


def linalg_test():
    """
    :return:
    """
    X = np.random.randn(5, 5)
    print(X)

    print("---------------------------mat------------------------")
    mat = X.T.dot(X)
    print(mat)

    print("-------------------------inv(mat)----------------------")
    i = inv(mat)
    print(i)

    print("------------------------mat.dot(i)---------------------")
    mi = mat.dot(i)
    print(mi)

    print("-------------------------qr(mat)-----------------------")
    q, r = qr(mat)
    print("---------------------------q---------------------------")
    print(q)
    print("---------------------------r---------------------------")
    print(r)


def walk_random():
    """
    随机漫步
    :return:
    """
    nsteps = 1000
    draws = np.random.randint(0, 2, size=nsteps)
    steps = np.where(draws > 0, 1, -1)
    walk = steps.cumsum()

    min = walk.min()
    print("min: ", min)

    max = walk.max()
    print("max: ", max)

    index = (np.abs(walk) >= 10).argmax()
    print("index: ", index)


def main():
    # save_data_to_byte()

    # save_write_txt()

    # linalg_test()

    walk_random()


if __name__ == "__main__":
    main()
